package com.swpu.service_sport.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.swpu.service_sport.entity.SportRecord;
import com.swpu.service_sport.entity.vo.SportRecordVo;
import com.swpu.service_sport.mapper.SportRecordMapper;
import com.swpu.service_sport.service.SportRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.swagger.models.auth.In;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chaichai
 * @since 2024-02-23
 */
@Service
public class SportRecordServiceImpl extends ServiceImpl<SportRecordMapper, SportRecord> implements SportRecordService {

    @Override
    public void saveUserSportRecord(String openid, SportRecord sportRecord) {
        sportRecord.setUserId(openid);
        boolean isSave = this.save(sportRecord);
        if(!isSave){
            throw new RuntimeException("用户运动数据保存失败");
        }
    }

    @Override
    public List<SportRecordVo> getUserSportRecord(String openid, Date date) {
        DateTime beginOfDay = DateUtil.beginOfDay(date);
        DateTime endOfDay = DateUtil.endOfDay(date);
        List<SportRecordVo> sportRecordVos = baseMapper.getUserSportRecordByDate(openid, beginOfDay, endOfDay);

        return sportRecordVos;

    }

    @Override
    public void deleteSportRecordById(String openid, String id) {
        LambdaQueryWrapper<SportRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SportRecord::getId,id);
        boolean isRemove = this.remove(queryWrapper);
        if (!isRemove){
            throw new RuntimeException("用户运动数据删除失败");
        }
    }
    @Override
    public int getSportCountByDate(String openid, Date queryDate) {
        LambdaQueryWrapper<SportRecord> queryWrapper = new LambdaQueryWrapper<>();
        DateTime beginOfDay = DateUtil.beginOfDay(queryDate);
        DateTime endOfDay = DateUtil.endOfDay(queryDate);
        queryWrapper.eq(SportRecord::getUserId,openid).between(SportRecord::getRecordTime,beginOfDay,endOfDay);
        int count = count(queryWrapper);
        return count;
    }

    @Override
    public Integer getSportCaloriesByDate(String openid, Date queryDate) {
        DateTime beginOfDay = DateUtil.beginOfDay(queryDate);
        DateTime endOfDay = DateUtil.endOfDay(queryDate);
        List<SportRecordVo> userSportRecordByDate = baseMapper.getUserSportRecordByDate(openid, beginOfDay, endOfDay);
        int calories=0;
        for (SportRecordVo sportRecordVo : userSportRecordByDate) {
            calories+=sportRecordVo.getCaloriesBurned()*1.0/sportRecordVo.getMinutes()*sportRecordVo.getRealMinutes();
        }
        return calories;
    }
}
